import isPlainObject from 'lodash/isPlainObject';
import { set, has } from 'lodash';
import isEqual from 'lodash/isEqual';
import { mapNodes, getUniqueID } from '@/utils/utils';

export function serialize(tree) {
  return mapNodes(tree, node => {
    if (typeof node.id !== 'string') {
      node.id = getUniqueID('_id');
    }

    if (!isPlainObject(node.state)) {
      node.state = {
        expanded: true,
      };
    }

    return node;
  });
}

/**
 * 设置指定nodePath的节点，node.state.selected = true，
 * 其余节点 移除state.selected
 * @param {*} tree
 * @param {*} nodePath
 * @returns
 */
export function serialize2(tree, nodePath) {
  let result = tree;

  if (Array.isArray(nodePath) && Array.isArray(tree)) {
    result = mapNodes(tree, k => {
      if (isEqual(k.nodePath, nodePath)) {
        return set(k, 'state.selected', true);
      }

      if (has(k, 'state.selected')) {
        delete k.state.selected;
      }

      return k;
    });
  }

  return result;
}

/**
 * 按顺序contains，比如 contains([a, b, c, d], [b, d]) == true
 */
export function contains(arr1, arr2) {
  if (!arr2 || arr2.length === 0) {
    return true;
  }

  if (!arr1 || arr1.length === 0) {
    return false;
  }

  let cursor = 0;

  for (let i = 0; i < arr1.length; i++) {
    const ele = arr1[i];

    if (ele === arr2[cursor] || (cursor === arr2.length - 1 && ele.includes(arr2[cursor]))) {
      cursor++;
      if (cursor === arr2.length) {
        return true;
      }
    }
  }

  return false;
}

export const TreeFilter = searchTerm => node => {
  const { nodePath = [], nodeName } = node;

  const upperCaseSearchTerm = searchTerm.toUpperCase();
  const upperCaseNodeName = nodeName.toUpperCase();
  const upperCasePaths = nodePath.map(p => p.toUpperCase());
  const searchPaths = upperCaseSearchTerm.split('.').filter(Boolean);

  return contains(upperCasePaths, searchPaths) || upperCaseNodeName.includes(upperCaseSearchTerm);
};
